﻿using Coldairarrow.Entity.Base;
using Coldairarrow.Entity.DTO;
using Coldairarrow.Entity.PB;
using Coldairarrow.IBusiness;
using Coldairarrow.Util;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace Coldairarrow.Business.PB
{
    public partial class PB_DesignDetailBusiness : BaseBusiness<PB_DesignDetail>, IPB_DesignDetailBusiness, ITransientDependency
    {
        readonly IOperator _operator;
        public PB_DesignDetailBusiness(IDbAccessor db, IOperator @operator)
            : base(db)
        {
            _operator = @operator;
        }

        #region 外部接口

        public async Task<PageResult<PB_DesignDetail>> GetDataListAsync(PageInput<ConditionDTO> input)
        {
            var q = GetIQueryable();
            var where = LinqHelper.True<PB_DesignDetail>();
            var search = input.Search;

            //筛选
            if (!search.Condition.IsNullOrEmpty() && !search.Keyword.IsNullOrEmpty())
            {
                var newWhere = DynamicExpressionParser.ParseLambda<PB_DesignDetail, bool>(
                    ParsingConfig.Default, false, $@"{search.Condition}.Contains(@0)", search.Keyword);
                where = where.And(newWhere);
            }

            return await q.Where(where).GetPageResultAsync(input);
        }

        public async Task<PB_DesignDetail> GetTheDataAsync(string id)
        {
            return await GetEntityAsync(id);
        }

        public async Task AddDataAsync(PB_DesignDetail data)
        {
            await InsertAsync(data);
        }

        public async Task UpdateDataAsync(PB_DesignDetail data)
        {
            await UpdateAsync(data);
        }

        public async Task DeleteDataAsync(List<string> ids)
        {
            await DeleteAsync(ids);
        }

        public async Task<List<PB_DesignDetailDTO>> GetDataListAsyncs(string ParentId)
        {
            Expression<Func<PB_DesignDetail, PB_Material, PB_MaterialType, PB_DesignDetailDTO>> select = (a, b, c) => new PB_DesignDetailDTO
            {
                MaterialID = b.Id,//物料编号
                MaterialName = b.Name,//物料名称
                MaterialTypeId = c.Name,//类型名称
                MaterialCode = b.Code,//物料编号
                Weight = b.Weight,//理论重量


            };
            select = select.BuildExtendSelectExpre();
            var q = from a in GetIQueryable().AsExpandable()
                    join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<PB_MaterialType>() on b.MaterialTypeId equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    select @select.Invoke(a, b, c);
            //筛选
            if (!ParentId.IsNullOrEmpty())
            {
                q = q.Where(w => w.ParentId == ParentId);
            }
            var res = await q.ToListAsync();

            return res;
        }

        public  List<DataTypeDTO> GetTypeAsyncs(string ParentId)
        {
            Expression<Func<PB_DesignList,PB_DesignDetail, PB_Material, PB_MaterialType, DataTypeDTO>> select = (e,a, b, c) => new DataTypeDTO
            {
                MaterialID = b.Id,//物料编号
                MaterialName = b.Name,//物料名称
                MaterialTypeId = c.Name,//类型名称
                MaterialCode = b.Code,//物料编号
            };
            select = select.BuildExtendSelectExpre();
            var q =
                 from e in Db.GetIQueryable<PB_DesignList>()
                  join a in Db.GetIQueryable<PB_DesignDetail>() on e.Id equals a.ParentId into eb
                 from a in eb.DefaultIfEmpty()
                    join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<PB_MaterialType>() on b.MaterialTypeId equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                   
                    select @select.Invoke(e,a, b, c);
            //筛选
            if (!ParentId.IsNullOrEmpty())
            {
                q = q.Where(w => w.Id == ParentId);
            }
            return  q.ToList();
        }

        public IQueryable<T> GetQueryable<T>() where T : class, new()
        {
            return Db.GetIQueryable<T>();
        }
        public async Task<List<DataTypeReturnInfo>> GetTypeAsyncsInfo(string ParentId)
        {
            Expression<Func<PB_DesignDetail, PB_Material, PB_MaterialType, PB_DesignDetailDTO>> select = (a, b, c) => new PB_DesignDetailDTO
            {
                MaterialID = b.Id,//物料编号
                MaterialName = b.Name,//物料名称
                MaterialTypeId = c.Name,//类型名称
                MaterialCode = b.Code,//物料编号
                Weight = b.Weight,//理论重量
                TypeID = c.Id//物料类型id
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in GetIQueryable().AsExpandable()
                    join b in Db.GetIQueryable<PB_Material>() on a.MaterialId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<PB_MaterialType>() on b.MaterialTypeId equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    select @select.Invoke(a, b, c);
            //筛选
            if (!ParentId.IsNullOrEmpty())
            {
                q = q.Where(w => w.ParentId == ParentId);
            }
            var res = await q.ToListAsync();

            List<DataTypeReturnInfo> dataTypeInfos = new List<DataTypeReturnInfo>();
            List<IGrouping<string, PB_DesignDetailDTO>> fenzu = res.ToList().GroupBy(P => P.MaterialTypeId).ToList();
            DataTypeReturnInfo dataTypeInfo = new DataTypeReturnInfo();
            foreach (IGrouping<string, PB_DesignDetailDTO> item in fenzu)
            {
                dataTypeInfo.TypeName = item.Key;
                dataTypeInfo.Sub = item.ToList();
                dataTypeInfos.Add(dataTypeInfo);
            }
            return dataTypeInfos;
        }

        public async Task AddDataExlAsync(List<PB_DesignDetail> data)
        {
            await Db.InsertAsync<PB_DesignDetail>(data);
        }
        public async Task AddDataExlAsync(List<PB_DesignDetail> data,string id)
        {
            await Db.InsertAsync<PB_DesignDetail>(data);
            //2022-03-04 朱柏清 项目执行过程明细
            PB_DesignList pB_DesignList = Db.GetIQueryable<PB_DesignList>().Where(s => s.Id == id).FirstOrDefault();
            PB_ProjectProcess pB_ProjectProcess = new PB_ProjectProcess
            {
                Id = IdHelper.GetId(),
                ProjectId = pB_DesignList.ProjectId,
                ProjectName = pB_DesignList.ProjectName,
                ProcessType = Db.GetIQueryable<Base_EnumItem>().Where(u => u.EnumCode.Contains("ProjectProcessType") && u.Name.Contains("设计清单")).FirstOrDefault().Value,
                BuildingnumberId = pB_DesignList.BuildingNumberID,
                BuildingnumberName = Db.GetIQueryable<PB_Buildingnumber>().Where(u => u.Id == pB_DesignList.BuildingNumberID).FirstOrDefault().Buildingnumber,
                Remarks = "变更",
                CreatorId = _operator.UserId,
                CreatorRealName = _operator.Property.RealName,
                CreateTime = DateTime.Now,
                OrderId= pB_DesignList.Id,
                Deleted = false,
            };
            await Db.InsertAsync<PB_ProjectProcess>(pB_ProjectProcess);
        }
        public async Task UpdateDataExlAsync(PB_DesignDetail data)
        {
            await ExecuteSqlAsync("update PB_DesignDetail  SET Nums='"+data.Nums+"' where Id='" + data. Id+ "'  and  Parentid='"+data.ParentId+"'  ");
        }

        #endregion

        #region 私有成员

        #endregion
    }
}